using EnvDTE;
using EnvDTE80;
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace AvaloniaMaidVSIX.Avalonia
{
    public class AxamlDocument : IDisposable
    {
        private Document _document;
        private string _file;

        public AxamlDocument(DTE2 dte, string file)
        {
            _document = GetDocument(dte, file);
            _file = file;
        }

        public void Dispose()
        {
            if (_document is null) return;
            Marshal.ReleaseComObject(_document);
            _document = null;
        }

        private Document GetDocument(DTE2 dte, string file)
        {
            var documents = dte.Documents;
            var count = documents.Count;
            for (int i = 1; i <= count; i++)
            {
                var document = documents.Item(i) as Document;
                if (document is null) continue;
                if (document.ProjectItem.FileNames[1] == file)
                {
                    return document;
                }
            }

            return null;
        }

        public void InsertXmlns(string xmlnsCode)
        {
            var lineCount = 0;
            var hasXml = false;
            using (var reader = new StreamReader(_file))
            {
                while (reader.EndOfStream == false)
                {
                    lineCount++;
                    var line = reader.ReadLine();
                    if (line is null) break;
                    if (IsXmlDeclared(line))
                    {
                        hasXml = true;
                        break;
                    }
                }
            }

            if (hasXml == false) return;
            var textDocument = _document;
            var textSelection = textDocument.Selection as TextSelection;
            if (textSelection is null) return;

            textSelection.MoveToLineAndOffset(lineCount, 1);
            textSelection.Insert(xmlnsCode);
        }

        private bool IsXmlDeclared(string text)
        {
            const string XmlnsToken = "xmlns:";
            return text.Contains(XmlnsToken);
        }

    }
}
